import styles from "./Example.module.scss";
import { Avatar, Card, Spin, Tabs, TabsProps } from "antd";
import {
  EyeOutlined,
  HeartOutlined,
  StarOutlined,
  UserOutlined,
} from "@ant-design/icons";
import axios from "@/utils/request.ts";
import localforage from "localforage";
import { useEffect, useState } from "react";
import useWinOpen from "@/hooks/useWinOpen.ts";
interface ExampleItem {
  name: string;
  url: string;
  data: string;
}
type ArrJson = { type: string; list: string[] };
const STATIC_URL = import.meta.env.VITE_APP_STATIC_URL;
function getRndInteger(min: number, max: number) {
  return Math.floor(Math.random() * (max - min)) + min;
}
const CardItem = ({ item, index }: { item: ExampleItem; index: number }) => {
  const WinOpen = useWinOpen();
  const [loading, setLoading] = useState(false);
  const handlePreview = (item: { name?: string; url?: string; data: any }) => {
    setLoading(true);
    axios.get(item.data).then((r) => {
      localforage
        .setItem("meta2d", JSON.stringify(r.data))
        .then(() => {
          WinOpen(`/`);
        })
        .catch((error) => {
          console.error("Error storing data:", error);
        })
        .finally(() => setLoading(false));
    });
  };
  return (
    <Spin spinning={loading}>
      <Card
        onClick={() => handlePreview(item)}
        hoverable
        className={"cardItem"}
        key={"card" + index}
        style={{ width: 300 }}
        bodyStyle={{ padding: 10 }}
        cover={
          <img
            alt="example"
            style={{ width: 350, height: 166 }}
            src={item.url}
          />
        }
      >
        <div className={"flex cardInfo"}>
          <section>
            <div>{item.name}</div>
            <div className={"iconList"}>
              <span>
                <EyeOutlined />
                {getRndInteger(0, 1000)}
              </span>
              <span>
                <HeartOutlined />
                {getRndInteger(0, 200)}
              </span>
              <span>
                <StarOutlined /> {getRndInteger(0, 50)}
              </span>
            </div>
          </section>
          <Avatar icon={<UserOutlined />} />
        </div>
      </Card>
    </Spin>
  );
};
export default function Example() {
  const [exampleList, setExampleList] = useState<ExampleItem[]>([]);
  const [arr, setArr] = useState<ArrJson[]>([]);
  const items: TabsProps["items"] = arr.map((v) => {
    return {
      key: v.type,
      label: v.type,
      children: null,
    };
  });

  const onChange = (arr: ArrJson[], key: string) => {
    let item = arr.find((v) => v.type == key);
    if (item != void 0) {
      setExampleList(() => {
        return (
          item?.list.map((it) => {
            return {
              name: it,
              url: `${STATIC_URL}/static/example/${it}.png`,
              data: `${STATIC_URL}/static/example/${it}.json`,
            };
          }) || []
        );
      });
    }
  };
  useEffect(() => {
    axios.get(`${STATIC_URL}/static/example/index.json`).then((r) => {
      let rows: ArrJson[] = [
        {
          type: "全部",
          list: r.data.map((v: ArrJson) => v.list).flat(Infinity),
        },
        ...r.data,
      ];
      setArr(rows);
      onChange(rows, rows[0]["type"]);
    });
  }, []);
  return (
    <div className={styles.container}>
      <header>
        <Tabs
          tabBarGutter={60}
          size={"large"}
          centered
          onChange={(k: string) => onChange(arr, k)}
          defaultActiveKey="全部"
          items={items}
        />
      </header>
      <main>
        <div className={"cards"}>
          {exampleList.map((item, index) => {
            return (
              <CardItem item={item} index={index} key={"CardItem" + index} />
            );
          })}
        </div>
      </main>
    </div>
  );
}
